<template>
  <div class="page-wrap">
    <div class="page-content">
      <el-card class="box-card">
        <template #header>
          <div class="flex">
            <div class="card-header flex-1">品聘导出处理</div>
            <el-link :icon="Download" href="/xlsx-ppin-builder/品聘导出模板.csv" target="_blank">下载模板</el-link>
          </div>
        </template>
        <el-upload :on-change="handleChange" :on-exceed="handleExceed" :accept="'.xlsx,.csv'" :limit="1" :auto-upload="false" drag action="#" multiple>
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">拖动文件到此处，或 <em>点击上传</em></div>
        </el-upload>
        <template #footer>
          <el-text size="small">将导出的异常数据恢复正常</el-text>
          <el-divider direction="vertical" />
          <el-text size="small"><el-link href="https://gitee.com/cvpv/xlsx-ppin-builder" target="_blank">https://gitee.com/cvpv/xlsx-ppin-builder</el-link></el-text>
        </template>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import * as XLSX from 'xlsx'
import { Download, UploadFilled } from '@element-plus/icons-vue'
import { ElMessage, ElNotification } from 'element-plus'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.extend(customParseFormat)

let selectedFile: File

const parseFile = () => {
  const fileReader = new FileReader()

  fileReader.onload = (event) => {
    // const data = new Uint8Array(event.target?.result as ArrayBuffer)
    const workbook = XLSX.read(event.target?.result, { type: 'binary', raw: true })

    // 获取第一个工作表
    const worksheet = workbook.Sheets[workbook.SheetNames[0]]

    // 将工作表数据转换为JSON对象
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 2, raw: true })

    // 处理解析后的数据
    console.log(jsonData)

    // 处理解析后的数据
    const newData = addTestDataColumn(jsonData)
    console.log('处理后的数据：')
    console.log(newData)
    exportToExcel(newData, 'resume.xlsx')
  }

  selectedFile && fileReader.readAsArrayBuffer(selectedFile)
}

const dateBuilder = (date: any) => {
  let newData = ''
  if (dayjs(String(date), 'YYYY', true).isValid()) {
    newData = dayjs(String(date), ['YYYY']).format('YYYY')
  } else {
    newData = dayjs(String(date), ['YYYY.MM', 'YYYY-MM', 'YYYY.M', 'YYYY/MM', 'MMM-YY']).format('YYYY.MM')
  }
  console.log('日期转码：', date, newData)
  return newData
}

const addTestDataColumn = (data: any) => {
  const _data: any = []
  let index = 0
  let total = data.length
  let progress = 0

  for (let i = 0; i < total; i++) {
    if (Object.keys(data[i]).length === 1) {
      if (!_data[index].advantage) {
        _data[index].advantage = '' // 有时候shen'r'g'ji有时候
      }
      _data[index].advantage += '\n' + data[i][Object.keys(data[i])[0]]
      data[i]
      _data.push({})
    } else {
      if (data[i].YearE) {
        console.log(JSON.parse(JSON.stringify(data[i])))
        data[i].YearE = dateBuilder(data[i].YearE)
      }
      if (data[i].YearB) {
        console.log(JSON.parse(JSON.stringify(data[i])))
        data[i].YearB = dateBuilder(data[i].YearB)
      }
      _data.push({
        ...data[i],
      })
      index = i
    }

    let newProgress = Math.floor(((i + 1) / total) * 100)
    if (newProgress !== progress) {
      console.log(`${newProgress}% completed`)
      progress = newProgress
    }
  }
  return _data.filter((item: any) => Object.keys(item).length !== 0)
  // return data.map((row: any, _index: number) => {
  //   const zheng_wen = row['正文'] || ''
  //   return {
  //     ...row,
  //     摘要: extractString(zheng_wen),
  //     正文网页: textToHtml(zheng_wen),
  //   }
  // })
}

const exportToExcel = (data: any, filename: string) => {
  ElMessage({
    message: `转换成功！`,
    type: 'success',
  })
  ElNotification({
    title: '提示',
    message: `如果浏览器拦截下载，请点击允许。如果要再次上传请刷新网页，以便清空状态。使用中有任何问题，请联系我。`,
    type: 'info',
    duration: 0,
  })
  const worksheet = XLSX.utils.json_to_sheet(data)
  const newWorkbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(newWorkbook, worksheet, 'Sheet1')
  XLSX.writeFile(newWorkbook, filename)
}

const handleExceed = () => {
  ElMessage({
    message: `最多选择${1}个文件`,
    type: 'warning',
  })
}
const handleChange = (rawFile: any, uploadFiles: any) => {
  console.log('触发改变')
  console.log(rawFile, uploadFiles)
  selectedFile = rawFile.raw
  parseFile()
}
</script>

<style scoped>
.flex {
  display: flex;
}
.flex-1 {
  flex: 1 1 0%;
}
.page-wrap {
  padding: 12vmin 4vmin;
  width: 100%;
  height: 100%;
  background-image: url('@/assets/beams.jpg');
  background-size: cover;
}
.page-content {
  max-width: none;
  margin: 0 auto;
}

/* 移动优先 响应式媒体查询 */
@media (min-width: 768px) {
  .page-wrap {
    padding: 32px;
    padding-top: 200px;
  }
  .page-content {
    max-width: 700px;
  }
}
</style>
